package com.yuezhi.producer.config;

import com.yuezhi.producer.constant.QueueConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    private static final Integer DELAY_TIME = 10 * 1000;

    @Bean
    Queue delayQueue() {
        Map<String,Object> map = new HashMap<>();
        map.put("x-message-ttl", DELAY_TIME);
        return new Queue(QueueConstant.TTL_QUEUE,true, false,false, map);
    }

    @Bean
    DirectExchange delayExchange() {
        return new DirectExchange(QueueConstant.TTL_EXCHANGE,true,false);
    }

    @Bean
    Binding delayBinding(){
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with("ttl");
    }

    /**
     * 设置消息队列发送RPC队列
     */
    @Bean
    Queue rpcQueueSend() {
        return new Queue(QueueConstant.RPC_QUEUE_ONE);
    }

    /**
     * 设置RPC返回队列
     */
    @Bean
    Queue rpcQueueReply() {
        return new Queue(QueueConstant.RPC_QUEUE_TWO);
    }

    /**
     * 设置RPC交换机
     */
    @Bean
    TopicExchange rpcExchange() {
        return new TopicExchange(QueueConstant.RPC_EXCHANGE);
    }

    /**
     * 请求队列与交换机绑定
     */
    @Bean
    Binding rpcBindingSend() {
       return BindingBuilder.bind(rpcQueueSend()).to(rpcExchange()).with(QueueConstant.RPC_QUEUE_ONE);
    }

    /**
     * 返回队列与交换机绑定
     */
    @Bean
    Binding rpcBindingReply() {
        return BindingBuilder.bind(rpcQueueReply()).to(rpcExchange()).with(QueueConstant.RPC_QUEUE_TWO);
    }

    /**
     * 使用RabbitTemplate发送和接受消息
     * 并设置回调队列地址
     * @param connectionFactory 连接工厂
     */
    @Bean
    RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setReplyAddress(QueueConstant.RPC_QUEUE_TWO);
        return rabbitTemplate;
    }

    /**
     * 给返回队列设置监听器
     */
    @Bean
    SimpleMessageListenerContainer replyContainer(ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer simple = new SimpleMessageListenerContainer();
        simple.setConnectionFactory(connectionFactory);
        simple.setQueueNames(QueueConstant.RPC_QUEUE_TWO);
        simple.setMessageListener(rabbitTemplate(connectionFactory));
        return simple;
    }
}
